import { useCallback, useEffect, useRef, useState } from 'react'
import { INewsList, NewItem } from 'Src/typings/interface'
import { getNewsList } from '../api'
import { useLocalStorage } from './useLocalStorage'

// 处理 数据分页
function handlePageList(pageList: NewItem[], count: number = 10) {
  const len = pageList.length
  let index = 0
  let newData = []
  while (index < len) {
    newData.push(pageList.slice(index, (index += count)))
  }
  return newData
}

/**
 * 请求newsList数据的hook
 * @param onsucess 请求成功后的回调
 * @param onDoFetch 每次请求参数变化的 副作用
 * @returns
 */
const useFetchNewsListApi = (
  onsucess?: (data: { newsType: string; pageList: NewItem[][]; pageIndex: number }) => void,
  onDoFetch?: (fetchData: (search: string) => void, search?: string, localData?: INewsList[]) => void,
): [
  { isLoading: boolean; isError: boolean; search: string },
  React.Dispatch<React.SetStateAction<string>>,
  React.Dispatch<React.SetStateAction<boolean>>,
] => {
  const [search, setSearch] = useState<string>('top')

  const [isLoading, setIsLoading] = useState(false)

  const [isError, setIsError] = useState(false)

  const localData = useLocalStorage<INewsList[]>('newsListState')

  const fetchData = useCallback(async (search: string) => {
    let result = null
    try {
      setIsLoading(true)
      result = await getNewsList(search)
      if (result.status === 200) {
        const data = {
          newsType: search,
          pageList: handlePageList(result.data.result.data),
          pageIndex: 0,
        }
        onsucess && onsucess(data)
      }
    } catch (error) {
      setIsError(true)
      setIsLoading(false)
    }
  }, [])

  // const ref = useRef(onDoFetch)
  // console.log(ref.current === onDoFetch)

  useEffect(() => {
    // search 传递进去 防止闭包陷阱，localData 传递进去减少内存不必要的消耗
    onDoFetch && onDoFetch(fetchData, search, localData)
  }, [search])

  return [{ isLoading, isError, search }, setSearch, setIsLoading]
}

export default useFetchNewsListApi
